<template>
	<view class="search-page">
		<view class="main-title">
			<view class="">商品选择</view>
			<view class="close-icons" @click="close">
				<uni-icons type="closeempty"></uni-icons>
			</view>
		</view>
		<view class="search-bar">
			<input v-model="searchKeyword" @input="handleSearch" placeholder="搜索商品名称、条码" @confirm="handleSearch" class="search-input" />
			<button @click="handleSearch" class="search-btn">搜索</button>
		</view>

		<view class="result-list" v-if="searchResults.length > 0">
			<view class="form_title">
				<view class="title barcode">条 码</view>
				<view class="title name">商品名称</view>
				<view class="title specs">规 格</view>
			</view>

			<view class="result-item" v-for="item in searchResults" :key="item._id" :class="{'selected':  isItemSelected(item._id)}" @click="toggleSelection(item)">
				<view class="grid barcode" style="font-weight: 600">
					<text class="item-barcode">{{getFirstValue(item.barcode, '无条码') }}</text>
				</view>
				<view class="grid name">
					<text>{{getFirstValue(item.goodName?.map(n=>n.goodName), '无名') }}</text>
				</view>

				<view class="grid specs">
					<text class="item-specs">{{getFirstValue(item.specs?.map(n=>n.specs),'无规格')}} </text>
				</view>
			</view>
		</view>

		<view class="empty-tip" v-else-if="searchKeyword">
			<view class="tip_one">
				<text>未找到"{{ searchKeyword }}"相关的记录</text>
			</view>

			<view class="tip_two" @click="handleCreate">
				<uni-icons type="compose" size="22" color="blue"></uni-icons>
				<text>申请建档</text>
			</view>
		
		</view>	
		<view class="sub_btn">
				<button type="primary" size="mini">选择</button>
				<button type="default" size="mini">退出</button>
			</view>
	</view>
</template>
<script>
const db = uniCloud.database();
const _ = db.command;
export default {
	name: 'goodDetail',

	data() {
		return {
			
			searchResults: [],
			searchKeyword: '',
			selected:[],
			selectedList:[],
			value: 1,
			isSelected:false
		};
	},
  computed: {
    selectedSet() {
      return new Set(this.selected);
    }
  },
  mounted() {	
	  console.log('000');
  this.initData()
  },
	methods: {
	async initData(){
		uni.showLoading({
			title:'加载中...'
		})
		try{ const result=await db.collection('product').get()
		  if(result.result.data.length>0){
			 this.searchResults=result.result.data 
		  }else{
			  this.searchResults=[]
		  }
		
		    }catch(e){
			console.error(e);
		}finally{
			uni.hideLoading()
		}
			
	},
		escapeRegExp(str) {
			return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
		},
		close() {
			this.$emit('close');
		},
		handleCreate() {
			uni.showToast({
				title: '没有权限'
			});
		},
		   getFirstValue(arr, defaultValue = '') {
		      return Array.isArray(arr) && arr.length > 0 ? arr[0] : defaultValue;
		    },
	    isItemSelected(id) {
	      return this.selectedSet.has(id);
	    },
	   toggleSelection(item) {
	      const id = item._id;
	      if (this.isItemSelected(id)) {
	        const index = this.selected.indexOf(id);
	        this.selected.splice(index, 1); // 响应式删除
			this.selectedList.splice(index,1)
	      } else {
	        this.selected.push(id); // 响应式添加
			this.selectedList.push(item)
	      }
	    },
		async handleSearch() {
			const escapedKeyword = this.escapeRegExp(this.searchKeyword);
			console.log('........', escapedKeyword);
			// 构建查询条件
			const queryCondition = {
				$or: [{ goodName: new db.RegExp({ regexp: escapedKeyword, options: 'i' }) }, { barcode: new db.RegExp({ regexp: escapedKeyword, options: 'i' }) }]
			};

			// 显示加载提示
			uni.showLoading({
				title: '搜索中...'
			});

			try {
	   
		const	result = await db.collection('product').where(queryCondition).get();
				
			

				console.log(' 搜索结果:', result);

				this.searchResults = result.result.data;
				uni.hideLoading();
			} catch (error) {
				console.error(' 搜索失败:', error.message, error.stack);
				uni.hideLoading();
				uni.showToast({
					title: '搜索失败，请重试',
					icon: 'none'
				});
			}
		},
		sureSubmit(){
		  uni.$emit("selctedList",this.selectedList)
           this.close()
		},
		nameChange() {}
	}
};
</script>
<style lang="scss" scoped>
.search-page {
	padding: 20rpx;
	background-color: #f5f5f5;
	position: absolute;
	left: 50%;
	transform: translate(-50%, -50%); /* 向上向左移动自身50% */
	top: 50%;
	z-index: 999;
	width: 70%;
	padding: 20rpx;
	  border: 2rpx solid #d5d7da;
	background-color: #f5f5f5;
}
.main-title {
	height: 100rpx;
	font-size: 40rpx;
	padding: 10rpx 20rpx;
	font-weight: 600;
	position: relative;
	.close-icons {
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		width: 50rpx;
		height: 50rpx;
		border-radius: 25rpx;
		background-color: white;
		right: 0;
		top: 0;
		:active {
			background-color: #666;
		}
	}
}
.search-bar {
	display: flex;
	align-items: center;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.selected{
	 background-color: #0055ff;
	 border-left: 10px solid #3b82f6;
	 transition: all 0.2s;
	 border-bottom: 1rpx solid #0055ff;
}
.search-input {
	flex: 1;
	height: 80rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	margin-right: 20rpx;
}

.search-btn {
	background-color: #409eff;
	color: #fff;
	border-radius: 8rpx;
	padding: 0 30rpx;
	height: 80rpx;
	font-size: 28rpx;
}

.result-list {
	display: flex;
	flex-direction: column;
	gap: 5rpx;
}

.result-item {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 10rpx;
	display: flex;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.form_title {
	display: flex;
	background-color: #dedede;
	.title {
		display: flex;
		padding: 10rpx 20rpx;
		background-color: #999;
		color: white;
		align-items: center;
		justify-content: center;
		margin: 5rpx;
		border-radius: 10rpx;
	}
}
.name {
	width: 25%;
}
.barcode {
	width: 20%;
}
.specs {
	width: 15%;
	/* 这行样式可能需要调整，因为在实际应用中可能需要不同的背景色 */
}
.grid {
	padding: 5rpx 20rpx;
	border-radius: 10rpx;
 
}
.item-name {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.item-specs,
.item-barcode {
	font-size: 28rpx;
	color: #666;
}

.empty-tip {
	display: flex;
	padding: 50rpx 50rpx;
	flex-direction: column;
	text-align: center;
	color: #999;
	font-size: 28rpx;
	.tip_one {
		margin-bottom: 50rpx;
	}
	.tip_two {
		color: blue;
		font-size: 35rpx;
	}
}
.sub_btn{
	display: flex;
	margin-top: 20rpx;
	align-items: center;
}
</style>
